import axios from "axios"
import storage from "@/utils/storage"
import { router } from "@/router/index"
let messageBoxFlag = 0 // 默认 MessageBox 未打开
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL + "/",
  timeout: 5000,
})
instance.interceptors.request.use(
  function (config: any) {
    if (storage.get("refresh_token")) {
      config.headers.authorization = `Bearer ${storage.get("refresh_token")}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
instance.interceptors.response.use(
  function (response) {
    if (response.data.code == 201) {
      console.log("refresh_token过期")
      if (messageBoxFlag === 0) {
        messageBoxFlag = 1 // 修改标记，打开 MessageBox
        ElMessageBox.confirm("登录超时，请重新登录，确定退出登录?")
          .then(() => {
            storage.clear()
            router.push({ path: "/" })
            ElNotification({
              title: "温馨提示",
              message: "已成功退出登录",
              type: "success",
            })
          })
          .catch(() => {
            ElNotification({
              title: "温馨提示",
              message: "已取消退出登录",
              type: "warning",
            })
          })
          .finally(() => {
            messageBoxFlag = 0 // 修改标记
          })
      }
      //   return response.data
    }
    return response.data
  },
  function (error) {
    if (error.code == "ERR_NETWORK") {
      ElMessage.error("服务器网络异常,请刷新后重试")
      //   router.push({ name: "login" })
      return Promise.reject({ code: 300, msg: "服务器网络异常,请刷新后重试" })
    }
    if (error.response) {
      const { status } = error.response
      console.log("====================================")
      console.log(status)
      console.log("====================================")
    }
    return Promise.reject(error)
  }
)
const Get = (url: string, params?: any) => instance.get(url, { params })
const Post = (url: string, data?: any) => instance.post(url, data)
const Put = (url: string, params?: any, data?: any) => instance.put(url, { params }, data)
const Delete = (url: string, params?: any) => instance.delete(url, { params })

export { Get, Post, Put, Delete, instance }
